package com.lstimeline.utility.DataManager;

import java.sql.*;
import java.util.HashMap;

import com.lstimeline.bean.Aces2SchoolBean;
/**
 * Provides StatusServlet with guids and school fullnames
 * @author Harry
 * @version Jun 2009
 */
public class StatusDataManager extends AbstractDataManager {
	/**
	 * Provide a complete list of supported schools for the Statuc Checker first page
	 */
	public static HashMap<Integer, String> getSchoolNameMap() {
		HashMap<Integer, String> schoolNames = new HashMap<Integer, String>();
		
		Connection conn = getConnection();
		if(conn != null) {
			PreparedStatement ps = null;
			ResultSet rs = null;
			try {
				//Ordered alphabatically
				String queryString = "SELECT * FROM school";
				
				ps = conn.prepareStatement(queryString);
				rs = ps.executeQuery();
				
				while(rs.next()) {
					schoolNames.put(rs.getInt(1), rs.getString(2));
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					rs.close();
					ps.close();
					
					closeConnection(conn);
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
			return schoolNames;
		} else {
			//conn not opened
			return null;
		}
	}
	
	/**
	 * Should be called exactly once when StatusSevlet initializes.
	 * @return the hashmap of guids
	 * 		null if failed
	 */
	public static HashMap<Integer, Aces2SchoolBean> getGuids() {
		boolean isSuccessful = false;
		
		HashMap<Integer, Aces2SchoolBean> guids = new HashMap<Integer, Aces2SchoolBean>();
		Connection conn = getConnection();
		if(conn != null) {
			PreparedStatement ps = null;
			ResultSet rs = null;
			try {
				String queryString = "SELECT schoolid, host, guid FROM aces2";
				ps = conn.prepareStatement(queryString);
				rs = ps.executeQuery();
				
				while(rs.next()) {
					Aces2SchoolBean bean = new Aces2SchoolBean();
					
					bean.setSchoolid(rs.getInt(1));
					bean.setHost(rs.getString(2));
					bean.setGuid(rs.getString(3));
					
					guids.put(bean.getSchoolid(), bean);
				}
				
				isSuccessful = guids.size() > 0;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					rs.close();
					ps.close();
					
					closeConnection(conn);
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
			
			if(isSuccessful) {
				return guids;
			} else {
				return null;
			}
		} else {
			//conn not opened
			return null;
		}
	}
}
